var express = require("express");
var router = express.Router();
var { ClueModel, AdminModel, clueHistoryModel } = require("../db/db");
var Objectid = require("mongodb").ObjectId;

router.get("/clue", async function (req, res) {
  var data = await ClueModel.find({});
  var admins = await AdminModel.find({})
  var historys = await clueHistoryModel.find({})
  res.send({
    code: 200, data: JSON.parse(JSON.stringify(data)).map(item => {
      return {
        ...item,
        creatorName: JSON.parse(JSON.stringify(admins)).find(item1 => item.Creator === item1._id)?.username,
        TheirMarketName: JSON.parse(JSON.stringify(admins)).find(item1 => item.TheirMarket === item1._id)?.username,
        cluehistory: JSON.parse(JSON.stringify(historys)).reduce((arr, item1) => {
          if (item1.clue == item._id) {
            arr.unshift({
              ...item1,
              salename: JSON.parse(JSON.stringify(admins)).find(item2 => item1.sale === item2._id)?.username,
            })
          }
          return arr
        }, []),
      }
    })
  });
});

router.post("/clue", async function (req, res) {
  if (req.body.WhatMarket == 1) {
    req.body.TheirMarket = req.body.Creator
  }
  await ClueModel.create({ ...req.body })
  res.send({ code: 200, message: '添加成功!' })
});

router.delete("/clue", async function (req, res) {
  var id = Objectid(req.query.id);
  await ClueModel.findByIdAndDelete({ _id: id }, function (err, data) {
    res.send({ message: "删除成功!", code: 200 });
  });
});

router.put("/clue", async function (req, res) {
  data = req.body;
  var id = Objectid(data["_id"]);
  await ClueModel.find({ _id: id }).update({ $set: data });
  res.send({ code: 200, message: '修改成功!' });
});

router.post('/clueHistory', async function (req, res) {
  await clueHistoryModel.create(req.body)
  await ClueModel.find({ _id: Objectid(req.body.clue) }).update({ $set: { TurnoverTime: new Date() } })
  res.send({ code: 200, message: '跟进成功!' })
})

module.exports = router;
